<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/Auth for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Auth\Controller;
use Application\Controller\AbstractController;
use Zend\View\Model\ViewModel;
use Auth\Model\ListEntity;
use Zend\Validator\ValidatorChain;
use Zend\Validator\EmailAddress;
use Mail\Mail;
use Zend\Mail\Message;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
use Zend\Crypt\Password\Bcrypt;
use Auth\Model\UserEntity;
use Zend\Stdlib\Hydrator\ClassMethods;
use Zend\Session\Container;
class IndexController extends AbstractController
{

    public function indexAction()
    {
        return array();
    }

    public function getPasswordAction()
    {       
        $request = $this->getRequest();
        if ($request->isPost()) {
            $email = $request->getPost('email');
            $validator = new ValidatorChain();
            $validator->attach(new EmailAddress());
            if (! $validator->isValid($email)) {
                $this->flashMessenger()->addErrorMessage('Invalid Email Format.');
                return $this->redirectToHome();
            }
            $existInList = $this->getListMapper()->_isExist($email);
            if(empty($existInList)) {
                $this->flashMessenger()->addErrorMessage('Permission denied.');
                return $this->redirectToHome();
            }
            $existInUsers = $this->getUserMapper()->_isExist($email);
            if(!empty($existInUsers)) {
                $this->flashMessenger()->addErrorMessage('Forgot password?');
                return $this->redirectToHome();
            } 
            $password = uniqid(mt_rand());
            $bcrypt = new Bcrypt();
            $salt = uniqid ( mt_rand () );
            $bcrypt->setSalt($salt);
            $hash = $bcrypt->create($password);
            $user = new UserEntity();
            $user->setEmail($email);
            $user->setPassword($hash);
            $user->setPasswordSalt($salt);
            $result = $this->getUserMapper()->addUser($user);
            $configs = $this->getSettingMapper()->getMailConfig(); 
            $mail = new Mail();
            $mail->setConfig($configs);
            $mail->setSubject('MBA Bootcamp Password');
            $from = $this->getSettingMapper()->getValue('mail_from');
            $name = $this->getSettingMapper()->getValue('mail_from_name');
            $mail->setFrom($from);
            $mail->setTo($email);
            $htmlMarkup = '<h1 style="color:red">Your Password : ' . $password . '</h1>';
            $html = new MimePart($htmlMarkup);
            $html->type = "text/html";
            $body = new MimeMessage();
            $body->setParts(array($html));
            $mail->setBody($body);
            $mail->send();
            if($result) {
                $this->flashMessenger()->addSuccessMessage('We has sent you an email, please check your inbox to get the password.');
                return $this->redirectToHome();
            }
        }
        return array();
    }
    public function loginAction()
    {
        $request=$this->getRequest();
        if($request->isPost()){
            //exit('222');
            $email=$request->getPost('email');
            $validator = new ValidatorChain();
            $validator->attach(new EmailAddress());
            if (! $validator->isValid($email)) {
                $this->flashMessenger()->addErrorMessage('Invalid Email Format.');
                return $this->redirectToHome();
            }
            $existInList = $this->getListMapper()->_isExist($email);
            if(empty($existInList)) {
                $this->flashMessenger()->addErrorMessage('Permission denied.');
                return $this->redirectToHome();
            }
            $existInUsers = $this->getUserMapper()->_isExist($email);
            /* if(!empty($existInUsers)) {
                $this->flashMessenger()->addErrorMessage('Forgot password?');
                return $this->redirectToHome();
            }
             */
            if(isset($email) && !empty($email)){
            $user=$this->getUserMapper()->getUserByEmail($email);
            if($user->getId()){
                $bcrypt = new Bcrypt();
        
                //print_r($user);exit();
                $new_hash = $bcrypt->setSalt($user->getPasswordSalt())->create($request->getPost('password'));
        
                $authAdapter = $this->getAuthService()->getAdapter();
                $authAdapter->setCredential($new_hash)->setIdentity($user->getEmail());
                $result = $authAdapter->authenticate();
                if($result->isValid()){
                    //exit('dddd');
                    $hyd = new ClassMethods();
        
                    $dataUser=$hyd->extract($user);
                    //print_r($dataUser);exit();
                    $this->setAuthSession($dataUser);
                    return $this->redirect()->toUrl('/learn');
                }
                else
                    exit('that bai');
            }
            }
            
        }
    }
    
    public function testAction()
    {
        $mail = new Mail();
        $mail->setUsername('nvd264@gmail.com');
        $mail->setPassword('20100930D5F964');
        $mail->setHost('smtp.googlemail.com');
        $mail->setPort('587');
        $mail->setSSL('tls');
        $mail->setSubject('Test');
        $mail->setFrom('nvd264@gmail.com' , 'Nguyen Dong');
        $mail->setTo('dong.php.it@gmail.com');
        $htmlMarkup = '<h1 style="color:red">Hello</h1>';
        $html = new MimePart($htmlMarkup);
        $html->type = "text/html";
        $body = new MimeMessage();
        $body->setParts(array($html));
        $mail->setBody($body);
        $mail->send();
        exit('send ok roi');
    }
    public function test2Action(){
        $request=$this->getRequest();
        if($request->isPost()){
            //exit('222');
            $email=$request->getPost('email');
            $user=$this->getUserMapper()->getUserByEmail($email);
            if($user->getId()){
                  $bcrypt = new Bcrypt();
                  
                  //print_r($user);exit();
                  $new_hash = $bcrypt->setSalt($user->getPasswordSalt())->create($request->getPost('password'));
                  
                  $authAdapter = $this->getAuthService()->getAdapter();
                  $authAdapter->setCredential($new_hash)->setIdentity($user->getEmail());
                  $result = $authAdapter->authenticate();
                  if($result->isValid()){
                      //exit('dddd');
                      $hyd = new ClassMethods();
                      
                      $dataUser=$hyd->extract($user);
                      //print_r($dataUser);exit();
                      $this->setAuthSession($dataUser);
                      return $this->redirect()->toUrl('/learn');
                  }
                  else 
                      exit('that bai');
            }
            
        }
        return new ViewModel(array(
            
            'email'=>$this->getAuthSession('email')
        ));
    }
    public function logoutAction(){
        $this->logout();
        //return $this->redirect()->toUrl('/');
    }
    public function logout(){
        $ss = new Container();
        $ss->getManager()->getStorage()->clear();
        $this->getAuthService()->clearIdentity();
        return $this->response;
    }
    
}
